package com.xxxx.yoyo.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxxx.yoyo.bean.Order;
import com.xxxx.yoyo.bean.Type;
import com.xxxx.yoyo.service.IOrderService;
import com.xxxx.yoyo.service.ITypeService;
import com.xxxx.yoyo.service.impl.OrderServiceImpl;
import com.xxxx.yoyo.service.impl.TypeServiceImpl;

/**
 * Servlet implementation class PayServlet
 */
@WebServlet("/index/pay")
public class PayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private IOrderService orderService = new OrderServiceImpl();
	private ITypeService typeService = new TypeServiceImpl();

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式为UTF-8,解决中文乱码
		request.setCharacterEncoding("UTF-8");
		
		//获取前端页面提交的参数(id,paytype,name,phone,address)
		String orderIdStr = request.getParameter("id");
		int orderId = Integer.parseInt(orderIdStr);
		String paytypeStr = request.getParameter("paytype");
		int paytype = Integer.parseInt(paytypeStr);
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		
		//根据订单id查询订单信息
		Order order = orderService.getOrderById(orderId);
		order.setStatus(2);//改为已付款
		order.setPaytype(paytype);//设置支付方式
		order.setName(name);
		order.setPhone(phone);
		order.setAddress(address);
		
		//更新订单信息
		boolean isSuccess = orderService.updateOrder(order);
		if(isSuccess) {//更新成功
			//设置成功信息
			request.setAttribute("msg", "恭喜你,支付成功!");
			
			//获取 [宠物分类] 列表
			List<Type> typeList = typeService.getTypeList();
			//把typeList存入request,方便/index/payok.jsp页面使用
			request.setAttribute("typeList", typeList);
			
			//请求转发,跳转到/index/payok.jsp页面
			request.getRequestDispatcher("/index/payok.jsp").forward(request, response);
		}else {//更新失败, 姓名或者收货地址的长度过长,就会失败
			//设置成功信息
			request.setAttribute("msg", "支付失败!收货人或者收货地址长度过长!");
			
			//获取 [宠物分类] 列表
			List<Type> typeList = typeService.getTypeList();
			//把typeList存入request,方便/index/payok.jsp页面使用
			request.setAttribute("typeList", typeList);
			
			//请求转发,跳转到/index/payok.jsp页面
			request.getRequestDispatcher("/index/payok.jsp").forward(request, response);

		}
	}

}
